const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs').promises;
const { spawn } = require('child_process');
const net = require('net');
const dgram = require('dgram');

// 引入统一的配置模块
const { defaultConfig } = require('./config.js');

// 模拟STUN客户端功能（在实际项目中，应该安装stun库：npm install stun）
// 这里提供一个简化的实现

const app = express();
const PORT = 5000;

// 中间件
app.use(cors());
app.use(express.json());

// 配置文件路径
const CONFIG_PATH = path.join(__dirname, '../config.json');

// 服务器状态
let serverStatus = 'stopped'; // unknown, running, stopped
let serverProcess = null;
let serverStartTime = null;





// 读取配置文件
async function readConfig() {
  try {
    const data = await fs.readFile(CONFIG_PATH, 'utf8');
    const config = JSON.parse(data);
    
    // 清理可能存在的嵌套结构
    if (config.success !== undefined) {
      delete config.success;
    }
    if (config.data !== undefined) {
      delete config.data;
    }
    
    // 将读取的配置与默认配置合并，确保所有必需字段都存在
    // 优先级: 配置文件 > 默认配置
    const mergedConfig = { ...defaultConfig, ...config };
    
    console.log('成功读取并合并配置文件');
    return mergedConfig;
  } catch (error) {
    console.error('读取配置文件失败:', error);
    // 如果文件不存在，创建默认配置文件
    const cleanDefaultConfig = { ...defaultConfig };
    await fs.writeFile(CONFIG_PATH, JSON.stringify(cleanDefaultConfig, null, 2));
    console.log('创建了新的默认配置文件');
    return cleanDefaultConfig;
  }
}

// 更新serverDZ.cfg文件中的配置项
async function updateServerDzCfg(config) {
  try {
    // 获取serverDZ.cfg文件路径
    const serverDir = path.join(__dirname, config.serverPath || '../DayZServer');
    const serverDzCfgPath = path.join(serverDir, config.serverCfgPath || 'serverDZ.cfg');
    
    // 检查文件是否存在
    if (!await fs.stat(serverDzCfgPath).catch(() => false)) {
      console.error(`serverDZ.cfg文件不存在: ${serverDzCfgPath}`);
      return false;
    }
    
    // 读取文件内容
    let cfgContent = await fs.readFile(serverDzCfgPath, 'utf8');
    
    // 更新基本服务器设置
    if (config.hostname !== undefined) {
      cfgContent = cfgContent.replace(
        /hostname\s*=\s*".*?"\s*;/,
        `hostname = "${config.hostname}";`
      );
    }
    
    if (config.password !== undefined) {
      cfgContent = cfgContent.replace(
        /password\s*=\s*".*?"\s*;/,
        `password = "${config.password}";`
      );
    }
    
    if (config.passwordAdmin !== undefined) {
      cfgContent = cfgContent.replace(
        /passwordAdmin=".*?";/,
        `passwordAdmin="${config.passwordAdmin}";`
      );
    }
    
    if (config.description !== undefined) {
      cfgContent = cfgContent.replace(
        /description=".*?";/,
        `description="${config.description}";`
      );
    }
    
    if (config.maxPlayers !== undefined) {
      cfgContent = cfgContent.replace(
        /maxPlayers\s*=\s*\d+;/,
        `maxPlayers = ${config.maxPlayers};`
      );
    }
    
    // 更新时间相关配置
    if (config.serverTime !== undefined) {
      cfgContent = cfgContent.replace(
        /serverTime=".*?";/,
        `serverTime="${config.serverTime}";`
      );
    }
    
    if (config.serverTimeAcceleration !== undefined) {
      cfgContent = cfgContent.replace(
        /serverTimeAcceleration\s*=\s*\d+(\.\d+)?;/,
        `serverTimeAcceleration = ${config.serverTimeAcceleration};`
      );
    }
    
    if (config.serverNightTimeAcceleration !== undefined) {
      cfgContent = cfgContent.replace(
        /serverNightTimeAcceleration\s*=\s*\d+(\.\d+)?;/,
        `serverNightTimeAcceleration = ${config.serverNightTimeAcceleration};`
      );
    }
    
    if (config.serverTimePersistent !== undefined) {
      cfgContent = cfgContent.replace(
        /serverTimePersistent\s*=\s*\d+;/,
        `serverTimePersistent = ${config.serverTimePersistent};`
      );
    }
    
    // 更新游戏设置
    if (config.respawnTime !== undefined) {
      cfgContent = cfgContent.replace(
        /respawnTime\s*=\s*\d+;/,
        `respawnTime = ${config.respawnTime};`
      );
    }
    
    if (config.enableDebugMonitor !== undefined) {
      cfgContent = cfgContent.replace(
        /enableDebugMonitor\s*=\s*\d+;/,
        `enableDebugMonitor = ${config.enableDebugMonitor};`
      );
    }
    
    if (config.maxPing !== undefined) {
      cfgContent = cfgContent.replace(
        /maxPing\s*=\s*\d+;/,
        `maxPing = ${config.maxPing};`
      );
    }
    
    if (config.minPing !== undefined) {
      cfgContent = cfgContent.replace(
        /minPing\s*=\s*\d+;/,
        `minPing = ${config.minPing};`
      );
    }
    
    if (config.freezeCheck !== undefined) {
      cfgContent = cfgContent.replace(
        /freezeCheck\s*=\s*\d+;/,
        `freezeCheck = ${config.freezeCheck};`
      );
    }
    
    // 更新网络和实例设置
    if (config.guaranteedUpdates !== undefined) {
      cfgContent = cfgContent.replace(
        /guaranteedUpdates\s*=\s*\d+;/,
        `guaranteedUpdates = ${config.guaranteedUpdates};`
      );
    }
    
    if (config.loginQueueConcurrentPlayers !== undefined) {
      cfgContent = cfgContent.replace(
        /loginQueueConcurrentPlayers\s*=\s*\d+;/,
        `loginQueueConcurrentPlayers = ${config.loginQueueConcurrentPlayers};`
      );
    }
    
    if (config.loginQueueMaxPlayers !== undefined) {
      cfgContent = cfgContent.replace(
        /loginQueueMaxPlayers\s*=\s*\d+;/,
        `loginQueueMaxPlayers = ${config.loginQueueMaxPlayers};`
      );
    }
    
    // 更新游戏机制设置
    if (config.forceSameBuild !== undefined) {
      cfgContent = cfgContent.replace(
        /forceSameBuild\s*=\s*\d+;/,
        `forceSameBuild = ${config.forceSameBuild};`
      );
    }
    
    if (config.disableVoN !== undefined) {
      cfgContent = cfgContent.replace(
        /disableVoN\s*=\s*\d+;/,
        `disableVoN = ${config.disableVoN};`
      );
    }
    
    if (config.vonCodecQuality !== undefined) {
      cfgContent = cfgContent.replace(
        /vonCodecQuality\s*=\s*\d+;/,
        `vonCodecQuality = ${config.vonCodecQuality};`
      );
    }
    
    if (config.disable3rdPerson !== undefined) {
      cfgContent = cfgContent.replace(
        /disable3rdPerson\s*=\s*\d+;/,
        `disable3rdPerson = ${config.disable3rdPerson};`
      );
    }
    
    if (config.disableCrosshair !== undefined) {
      cfgContent = cfgContent.replace(
        /disableCrosshair\s*=\s*\d+;/,
        `disableCrosshair = ${config.disableCrosshair};`
      );
    }
    
    if (config.disablePersonalLight !== undefined) {
      cfgContent = cfgContent.replace(
        /disablePersonalLight\s*=\s*\d+;/,
        `disablePersonalLight = ${config.disablePersonalLight};`
      );
    }
    
    if (config.lightingConfig !== undefined) {
      cfgContent = cfgContent.replace(
        /lightingConfig\s*=\s*\d+;/,
        `lightingConfig = ${config.lightingConfig};`
      );
    }
    
    // 更新网络范围和对象批处理设置
    if (config.networkRangeClose !== undefined) {
      cfgContent = cfgContent.replace(
        /networkRangeClose\s*=\s*\d+;/,
        `networkRangeClose = ${config.networkRangeClose};`
      );
    }
    
    if (config.networkRangeCloseMax !== undefined) {
      cfgContent = cfgContent.replace(
        /networkRangeCloseMax\s*=\s*\d+;/,
        `networkRangeCloseMax = ${config.networkRangeCloseMax};`
      );
    }
    
    if (config.networkRangeNear !== undefined) {
      cfgContent = cfgContent.replace(
        /networkRangeNear\s*=\s*\d+;/,
        `networkRangeNear = ${config.networkRangeNear};`
      );
    }
    
    if (config.networkRangeMedium !== undefined) {
      cfgContent = cfgContent.replace(
        /networkRangeMedium\s*=\s*\d+;/,
        `networkRangeMedium = ${config.networkRangeMedium};`
      );
    }
    
    if (config.networkRangeMediumMax !== undefined) {
      cfgContent = cfgContent.replace(
        /networkRangeMediumMax\s*=\s*\d+;/,
        `networkRangeMediumMax = ${config.networkRangeMediumMax};`
      );
    }
    
    if (config.networkRangeFar !== undefined) {
      cfgContent = cfgContent.replace(
        /networkRangeFar\s*=\s*\d+;/,
        `networkRangeFar = ${config.networkRangeFar};`
      );
    }
    
    if (config.networkRangeFarMax !== undefined) {
      cfgContent = cfgContent.replace(
        /networkRangeFarMax\s*=\s*\d+;/,
        `networkRangeFarMax = ${config.networkRangeFarMax};`
      );
    }
    
    if (config.networkRangeDistantEffect !== undefined) {
      cfgContent = cfgContent.replace(
        /networkRangeDistantEffect\s*=\s*\d+;/,
        `networkRangeDistantEffect = ${config.networkRangeDistantEffect};`
      );
    }
    
    // 更新对象批处理设置
    if (config.networkObjectBatchLogSlow !== undefined) {
      cfgContent = cfgContent.replace(
        /networkObjectBatchLogSlow\s*=\s*\d+;/,
        `networkObjectBatchLogSlow = ${config.networkObjectBatchLogSlow};`
      );
    }
    
    if (config.networkObjectBatchEnforceBandwidthLimits !== undefined) {
      cfgContent = cfgContent.replace(
        /networkObjectBatchEnforceBandwidthLimits\s*=\s*\d+;/,
        `networkObjectBatchEnforceBandwidthLimits = ${config.networkObjectBatchEnforceBandwidthLimits};`
      );
    }
    
    // 新增对象批处理相关配置参数
    if (config.networkObjectBatchMaxNumFarUnits !== undefined) {
      cfgContent = cfgContent.replace(
        /networkObjectBatchMaxNumFarUnits\s*=\s*\d+;/,
        `networkObjectBatchMaxNumFarUnits = ${config.networkObjectBatchMaxNumFarUnits};`
      );
    }
    
    if (config.networkObjectBatchMinSizeNearUnits !== undefined) {
      cfgContent = cfgContent.replace(
        /networkObjectBatchMinSizeNearUnits\s*=\s*\d+;/,
        `networkObjectBatchMinSizeNearUnits = ${config.networkObjectBatchMinSizeNearUnits};`
      );
    }
    
    if (config.networkObjectBatchMinSizeMediumUnits !== undefined) {
      cfgContent = cfgContent.replace(
        /networkObjectBatchMinSizeMediumUnits\s*=\s*\d+;/,
        `networkObjectBatchMinSizeMediumUnits = ${config.networkObjectBatchMinSizeMediumUnits};`
      );
    }
    
    if (config.networkObjectBatchMinSizeFarUnits !== undefined) {
      cfgContent = cfgContent.replace(
        /networkObjectBatchMinSizeFarUnits\s*=\s*\d+;/,
        `networkObjectBatchMinSizeFarUnits = ${config.networkObjectBatchMinSizeFarUnits};`
      );
    }
    
    if (config.maxMessageSize !== undefined) {
      cfgContent = cfgContent.replace(
        /maxMessageSize\s*=\s*\d+;/,
        `maxMessageSize = ${config.maxMessageSize};`
      );
    }
    
    // 新增视图距离相关配置参数
    if (config.objectViewDistance !== undefined) {
      cfgContent = cfgContent.replace(
        /objectViewDistance\s*=\s*\d+\.\d+;/,
        `objectViewDistance = ${config.objectViewDistance};`
      );
    }
    
    if (config.terrainGrid !== undefined) {
      cfgContent = cfgContent.replace(
        /terrainGrid\s*=\s*\d+;/,
        `terrainGrid = ${config.terrainGrid};`
      );
    }
    
    if (config.visibilityLimit !== undefined) {
      cfgContent = cfgContent.replace(
        /visibilityLimit\s*=\s*\d+;/,
        `visibilityLimit = ${config.visibilityLimit};`
      );
    }
    
    // 新增对象和安全相关配置参数
    if (config.maxCustomObjectFileSize !== undefined) {
      cfgContent = cfgContent.replace(
        /maxCustomObjectFileSize\s*=\s*\d+;/,
        `maxCustomObjectFileSize = ${config.maxCustomObjectFileSize};`
      );
    }
    
    if (config.onePlayerSleeperActivateDefense !== undefined) {
      cfgContent = cfgContent.replace(
        /onePlayerSleeperActivateDefense\s*=\s*\d+;/,
        `onePlayerSleeperActivateDefense = ${config.onePlayerSleeperActivateDefense};`
      );
    }
    
    if (config.timeToStartDefense !== undefined) {
      cfgContent = cfgContent.replace(
        /timeToStartDefense\s*=\s*\d+;/,
        `timeToStartDefense = ${config.timeToStartDefense};`
      );
    }
    
    if (config.timeToAutoShutdownDefense !== undefined) {
      cfgContent = cfgContent.replace(
        /timeToAutoShutdownDefense\s*=\s*\d+;/,
        `timeToAutoShutdownDefense = ${config.timeToAutoShutdownDefense};`
      );
    }
    
    if (config.serverSecure !== undefined) {
      cfgContent = cfgContent.replace(
        /serverSecure\s*=\s*\d+;/,
        `serverSecure = ${config.serverSecure};`
      );
    }
    
    if (config.advertise !== undefined) {
      cfgContent = cfgContent.replace(
        /advertise\s*=\s*\d+;/,
        `advertise = ${config.advertise};`
      );
    }
    
    if (config.limitFPS !== undefined) {
      cfgContent = cfgContent.replace(
        /limitFPS\s*=\s*\d+;/,
        `limitFPS = ${config.limitFPS};`
      );
    }
    
    if (config.disableWhitelist !== undefined) {
      cfgContent = cfgContent.replace(
        /disableWhitelist\s*=\s*\d+;/,
        `disableWhitelist = ${config.disableWhitelist};`
      );
    }
    
    if (config.disableBanlist !== undefined) {
      cfgContent = cfgContent.replace(
        /disableBanlist\s*=\s*\d+;/,
        `disableBanlist = ${config.disableBanlist};`
      );
    }
    
    if (config.remoteRconPassword !== undefined && config.remoteRconPassword !== '') {
      cfgContent = cfgContent.replace(
        /remoteRconPassword\s*=\s*"";/,
        `remoteRconPassword = "${config.remoteRconPassword}";`
      );
    }
    
    if (config.remoteRconPort !== undefined) {
      cfgContent = cfgContent.replace(
        /remoteRconPort\s*=\s*\d+;/,
        `remoteRconPort = ${config.remoteRconPort};`
      );
    }
    
    // 更新MOTD设置
    if (config.motd && Array.isArray(config.motd) && config.motd.length > 0) {
      const motdContent = config.motd.map(line => `    ${line}`).join('\n');
      cfgContent = cfgContent.replace(
        /(motd=\[\n)((?:    .*?\n)*)(\];)/,
        `$1${motdContent}\n$3`
      );
    }
    
    if (config.motdInterval !== undefined) {
      cfgContent = cfgContent.replace(
        /motdInterval=\d+;/,
        `motdInterval=${config.motdInterval};`
      );
    }
    
    // 写入更新后的内容
    await fs.writeFile(serverDzCfgPath, cfgContent);
    console.log('serverDZ.cfg已更新');
    return true;
  } catch (error) {
    console.error('更新serverDZ.cfg失败:', error);
    return false;
  }
}

// 保存配置文件
async function saveConfig(config) {
  try {
    // 确保备份路径配置存在且有效，始终使用相对路径
    if (!config.backupPath) {
      config.backupPath = 'backups';
    }
    
    // 确保addAtPrefix字段存在于配置中
    if (config.addAtPrefix === undefined) {
      config.addAtPrefix = false;
    }
    
    // 处理备份路径，基于backend目录的相对路径
    const backupDir = path.join(__dirname, config.backupPath);
    
    console.log(`使用备份路径: ${backupDir}`);
    
    await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2));
    
    // 更新serverDZ.cfg文件
    await updateServerDzCfg(config);
    
    return true;
  } catch (error) {
    console.error('保存配置文件失败:', error);
    return false;
  }
}

// API端点

// 获取服务器状态
app.get('/api/server/status', (req, res) => {
  res.json({
    data: {
      running: serverStatus === 'running',
      paused: serverStatus === 'paused',
      startTime: serverStartTime
    }
  });
});

// 启动服务器
app.post('/api/server/start', async (req, res) => {
  try {
    if (serverStatus === 'running') {
      return res.json({ success: false, message: '服务器已经在运行中' });
    }
    
    console.log('启动DayZ服务器...');
    
    // 读取配置
    const config = await readConfig();
    
    // 处理服务器路径
    let serverDir = config.serverPath || '../DayZServer';
    
    // 如果是相对路径，则相对于backend目录解析
    if (!path.isAbsolute(serverDir)) {
      serverDir = path.join(__dirname, serverDir);
    }
    
    // 标准化路径
    serverDir = path.normalize(serverDir);
    
    // DayZServer可执行文件路径
    const serverExePath = path.join(serverDir, config.serverExe || 'DayZServer_x64.exe');
    const pidFilePath = path.join(__dirname, 'pidServer.txt');
    
    // 验证服务器路径和可执行文件是否存在
    try {
      const stats = await fs.stat(serverExePath);
      if (!stats.isFile()) {
        throw new Error('服务器可执行文件不存在');
      }
    } catch (e) {
      return res.status(500).json({ success: false, message: `服务器路径无效或可执行文件不存在: ${serverExePath}` });
    }
    
    console.log(`使用服务器路径: ${serverDir}`);
    
    // 设置启动参数，基于配置文件和最佳实践
    // 更多详细信息请参考 https://community.bistudio.com/wiki/DayZ:Server_Configuration
    const missionTemplate = config.missionTemplate || 'dayzOffline.chernarusplus';
    
    // 构建启动参数 - 标准化使用等号格式
    const startArgs = [
      `-config=${config.serverCfgPath || 'serverDZ.cfg'}`,
      `-bepath=${config.battleyePath || 'battleye'}`,
      `-profiles=${config.profilesPath || 'profiles'}`,
      `-mission=mpmissions/${missionTemplate}`,
      `-port=${config.serverPort || 2302}`,
      `-rconPassword=${config.rconPassword || 'admin'}`,
      `-rconPort=${config.rconPort || 2305}`,
      `-log`,                  // 创建日志文件
      `-maxMem=${config.maxMemory || 4096}`, // 设置最大内存使用
      `-monitor`,              // 启用服务器监控
      `-enableHT`              // 启用高纹理支持
    ];
    
    // 根据配置添加布尔参数
    if (config.freezeCheck !== false) startArgs.push('-freezeCheck');
    if (config.adminLog !== false) startArgs.push('-adminLog');
    if (config.doLogs !== false) startArgs.push('-doLogs');
    
    // filePatching参数 - 统一使用正确的格式，不再使用单独的-noFilePatching参数
    startArgs.push(`-filePatching=${config.filePatching ? '1' : '0'}`);
    
    // 其他参数
      startArgs.push(`-scriptDebug=${config.scriptDebug || 0}`);
      startArgs.push(`-scrAllowFileWrite=${config.scrAllowFileWrite !== false ? '1' : '0'}`);
      // 添加安全与反作弊设置
      startArgs.push(`-speedhackDetection=${config.speedhackDetection || 1}`);
      startArgs.push(`-shotValidation=${config.shotValidation || 1}`);
      // 添加多账号缓解措施设置
      if (config.disableMultiAccountMitigation === true) {
        startArgs.push(`-disableMultiAccountMitigation`);
      }
    
    // 仅在需要时添加netLog，这会生成大量日志
      if (config.netLog === true) {
        startArgs.push(`-netLog`);
      }

      // 添加CPU核心数参数
      if (config.cpuCount && config.cpuCount > 0) {
        startArgs.push(`-cpuCount=${config.cpuCount}`);
      }

      // 添加FPS限制参数
      startArgs.push(`-limitFPS=${config.limitFPS || 100}`);

      // 添加服务器崩溃保护参数
      if (config.crashProtection !== false) {
        startArgs.push(`-crashguard`);
      }

      // 添加黑白名单和优先级列表相关参数
      if (config.disableBanlist === true) startArgs.push('-disableBanlist');
      if (config.disablePrioritylist === true) startArgs.push('-disablePrioritylist');
      if (config.enableWhitelist === 1) startArgs.push('-enableWhitelist');
      
      // 添加日志相关参数
      if (config.logPlayers === 1) startArgs.push('-logPlayers');

      // 如果有模组配置，添加模组参数
      if (config.mods && config.mods.length > 0) {
        // 分离客户端和服务器端模组，根据addAtPrefix设置决定参数格式
        const clientMods = config.mods.filter(mod => mod.type !== 'server').map(mod => {
          if (config.addAtPrefix === true) {
            // 如果勾选了@前缀，使用mod.name（如@CF）
            return mod.name;
          } else {
            // 如果未勾选@前缀，使用完整路径格式mods/CF，不加@
            const modName = mod.name.startsWith('@') ? mod.name.substring(1) : mod.name;
            return `mods/${modName}`;
          }
        });
        const serverMods = config.mods.filter(mod => mod.type === 'server').map(mod => {
          if (config.addAtPrefix === true) {
            // 如果勾选了@前缀，使用mod.name（如@CF）
            return mod.name;
          } else {
            // 如果未勾选@前缀，使用完整路径格式mods/CF，不加@
            const modName = mod.name.startsWith('@') ? mod.name.substring(1) : mod.name;
            return `mods/${modName}`;
          }
        });
        
        // 添加客户端模组参数 (-mod=)
        if (clientMods.length > 0) {
          const clientModsParam = `-mod=${clientMods.join(';')}`;
          startArgs.splice(1, 0, clientModsParam);
        }
        
        // 添加服务器端模组参数 (-serverMod=)
        if (serverMods.length > 0) {
          const serverModsParam = `-serverMod=${serverMods.join(';')}`;
          startArgs.splice(1, 0, serverModsParam);
        }
      }
    
    console.log('启动参数:', startArgs.join(' '));
    
    // 更新dayzsetting.xml配置文件（如果提供了相关配置）
    const dayzSettingPath = path.join(serverDir, 'dayzsetting.xml');
    try {
      if (await fs.stat(dayzSettingPath).catch(() => false)) {
        let settingContent = await fs.readFile(dayzSettingPath, 'utf8');
        
        // 更新CPU核心设置
        if (config.dayzsettingpcmaxcores !== undefined) {
          settingContent = settingContent.replace(
            /<pc\s+maxcores="\d+"\s+reservedcores="\d+"\s*\/>/,
            `<pc maxcores="${config.dayzsettingpcmaxcores}" reservedcores="${config.dayzsettingreservedcores || 1}" />`
          );
        }
        
        // 更新队列设置
        if (config.dayzsettingglobalqueue !== undefined || config.dayzsettingthreadqueue !== undefined) {
          settingContent = settingContent.replace(
            /<jobsystem\s+globalqueue="\d+"\s+threadqueue="\d+"\s*>/,
            `<jobsystem globalqueue="${config.dayzsettingglobalqueue || 4096}" threadqueue="${config.dayzsettingthreadqueue || 1024}">`
          );
        }
        
        await fs.writeFile(dayzSettingPath, settingContent);
        console.log('dayzsetting.xml 已更新');
      }
    } catch (settingError) {
      console.error('更新dayzsetting.xml失败:', settingError);
      // 继续执行，dayzsetting.xml更新失败不应该阻止服务器启动
    }
    
    // 启动DayZ服务器进程
    serverProcess = spawn(serverExePath, startArgs, {
      cwd: serverDir,
      detached: true,
      stdio: 'ignore'
    });
    
    // 保存PID到文件，使用相对路径
    try {
      // 写入PID到当前目录
      await fs.writeFile(pidFilePath, serverProcess.pid.toString());
      console.log(`PID ${serverProcess.pid} 已保存到 ${pidFilePath}`);
    } catch (pidError) {
      console.error('保存PID失败:', pidError);
      // 继续执行，PID保存失败不应该阻止服务器启动
    }
    
    // 解除与父进程的关联，让服务器可以在父进程关闭后继续运行
    serverProcess.unref();
    
    // 更新服务器状态和启动时间
    serverStatus = 'running';
    serverStartTime = new Date().toISOString();
    console.log('DayZ服务器启动成功，PID:', serverProcess.pid, '启动时间:', serverStartTime);
    res.json({ success: true, message: '服务器启动成功！', pid: serverProcess.pid });
  } catch (error) {
    console.error('启动服务器失败:', error);
    res.status(500).json({ success: false, message: `服务器启动失败: ${error.message}` });
  }
});

// 停止服务器
app.post('/api/server/stop', async (req, res) => {
  try {
    if (serverStatus === 'stopped') {
      return res.json({ success: false, message: '服务器已经停止' });
    }
    
    console.log('停止DayZ服务器...');
    
    const pidFilePath = path.join(__dirname, 'pidServer.txt');
    let pids = [];
    
    // 尝试从文件读取PID，模仿Server_manager.ps1的行为
    try {
      if (await fs.stat(pidFilePath).catch(() => false)) {
        const pidContent = await fs.readFile(pidFilePath, 'utf8');
        pids = pidContent.trim().split('\n').filter(pid => pid);
        console.log('从文件读取的PID列表:', pids);
      }
    } catch (pidError) {
      console.error('读取PID文件失败:', pidError);
    }
    
    // 如果没有从文件读取到PID，使用当前记录的进程
    if (pids.length === 0 && serverProcess) {
      pids = [serverProcess.pid.toString()];
      console.log('使用内存中的PID:', pids);
    }
    
    let allStoppedSuccessfully = true;
    
    // 对每个PID尝试停止进程，模仿Server_manager.ps1的优雅停止方式
    for (const pid of pids) {
      try {
        // 尝试优雅停止（发送关闭信号）
        const processToStop = require('child_process').exec(`tasklist /FI "PID eq ${pid}"`);
        
        setTimeout(() => {
          // 5秒后强制停止（如果还在运行）
          spawn('taskkill', ['/F', '/PID', pid], {
            stdio: 'ignore'
          });
        }, 5000);
        
        console.log(`发送停止信号到PID ${pid}`);
      } catch (stopError) {
        console.error(`停止PID ${pid}失败:`, stopError);
        allStoppedSuccessfully = false;
      }
    }
    
    // 如果没有具体PID，回退到按进程名停止
    if (pids.length === 0) {
      console.log('没有找到PID，尝试按进程名停止');
      const stopProcess = spawn('taskkill', ['/F', '/IM', 'DayZServer_x64.exe'], {
        stdio: 'pipe'
      });
      
      stopProcess.stdout.on('data', (data) => {
        console.log(`taskkill stdout: ${data}`);
      });
      
      stopProcess.stderr.on('data', (data) => {
        console.error(`taskkill stderr: ${data}`);
      });
      
      stopProcess.on('close', (code) => {
        if (code === 0) {
          console.log('DayZ服务器停止成功');
          allStoppedSuccessfully = true;
        } else {
          console.log('DayZ服务器进程不存在或停止失败');
          allStoppedSuccessfully = false;
        }
        
        // 清理PID文件
        fs.unlink(pidFilePath).catch(() => {
          console.log('PID文件不存在或已被删除');
        });
        
        // 更新状态
        serverProcess = null;
          serverStatus = 'stopped';
          serverStartTime = null;
          res.json({ success: allStoppedSuccessfully, message: '服务器停止操作已执行' });
      });
    } else {
      // 等待一段时间后检查进程是否真正停止
      setTimeout(() => {
        // 清理PID文件
        fs.unlink(pidFilePath).catch(() => {
          console.log('PID文件不存在或已被删除');
        });
        
        // 更新状态
        serverProcess = null;
        serverStatus = 'stopped';
        res.json({ success: allStoppedSuccessfully, message: '服务器停止操作已执行' });
      }, 1000);
    }
    
  } catch (error) {
    console.error('停止服务器失败:', error);
    res.status(500).json({ success: false, message: `服务器停止失败: ${error.message}` });
  }
});

// 获取配置
app.get('/api/config', async (req, res) => {
  try {
    const config = await readConfig();
    res.json({ success: true, data: config });
  } catch (error) {
    res.status(500).json({ success: false, message: '读取配置失败' });
  }
});

// 暂停服务器（模拟功能，实际DayZ服务器不支持暂停）
app.post('/api/server/pause', (req, res) => {
  try {
    if (serverStatus !== 'running') {
      return res.json({ success: false, message: '服务器未运行，无法暂停' });
    }
    
    console.log('暂停DayZ服务器...');
    serverStatus = 'paused';
    res.json({ success: true, message: '服务器已暂停' });
  } catch (error) {
    res.status(500).json({ success: false, message: `暂停服务器失败: ${error.message}` });
  }
});

// 恢复服务器（模拟功能）
app.post('/api/server/resume', (req, res) => {
  try {
    if (serverStatus !== 'paused') {
      return res.json({ success: false, message: '服务器未暂停，无法恢复' });
    }
    
    console.log('恢复DayZ服务器...');
    serverStatus = 'running';
    res.json({ success: true, message: '服务器已恢复运行' });
  } catch (error) {
    res.status(500).json({ success: false, message: `恢复服务器失败: ${error.message}` });
  }
});

// 获取服务器日志（模拟功能）
app.get('/api/server/logs', (req, res) => {
  try {
    const lines = req.query.lines || 50;
    // 这里返回模拟的日志数据，实际实现应该从日志文件读取
    res.json({
      success: true,
      data: {
        logs: '这是模拟的服务器日志数据\n当前没有真实的日志文件实现',
        file: 'server.log'
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: `获取日志失败: ${error.message}` });
  }
});

// 获取可用的任务模板列表
app.get('/api/mission-templates', async (req, res) => {
  try {
    // 读取配置以获取服务器路径
    const config = await readConfig();
    let serverDir = config.serverPath || '../DayZServer';
    
    // 如果是相对路径，则相对于backend目录解析
    if (!path.isAbsolute(serverDir)) {
      serverDir = path.join(__dirname, serverDir);
    }
    
    // 标准化路径
    serverDir = path.normalize(serverDir);
    
    // mpmissions目录路径
    const mpmissionsDir = path.join(serverDir, 'mpmissions');
    
    // 检查mpmissions目录是否存在
    try {
      await fs.stat(mpmissionsDir);
    } catch (e) {
      console.error('mpmissions目录不存在:', mpmissionsDir);
      // 返回成功状态但带有空模板数组，而不是错误
      return res.json({ templates: [] });
    }
    
    try {
      // 读取mpmissions目录中的所有文件夹
      const files = await fs.readdir(mpmissionsDir, { withFileTypes: true });
      const folders = files
        .filter(file => file.isDirectory())
        .map(folder => folder.name);
      
      // 为每个文件夹生成可读的名称（移除"Offline"后缀，添加空格等）
      const templates = folders.map(folder => ({
        value: folder,
        label: folder
          .replace(/\./g, ' ')
          .replace(/([A-Z])/g, ' $1')
          .replace(/^\s+/, '')
          .trim()
      }));
      
      res.json({ templates });
    } catch (readError) {
      console.error('读取mpmissions目录失败:', readError);
      // 返回成功状态但带有空模板数组
      res.json({ templates: [] });
    }
  } catch (error) {
    console.error('获取任务模板列表失败:', error);
    // 捕获所有错误，返回成功状态但带有空模板数组
    res.json({ templates: [] });
  }
});

// 读取mods文件夹中的模组
app.get('/api/read-mods-folder', async (req, res) => {
  try {
    // 读取配置以获取服务器路径
    const config = await readConfig();
    let serverDir = config.serverPath || '../DayZServer';
    
    // 如果是相对路径，则相对于backend目录解析
    if (!path.isAbsolute(serverDir)) {
      serverDir = path.join(__dirname, serverDir);
    }
    
    // 标准化路径
    serverDir = path.normalize(serverDir);
    
    // mods目录路径
    const modsDir = path.join(serverDir, 'mods');
    
    // 检查mods目录是否存在
    try {
      await fs.stat(modsDir);
    } catch (e) {
      // 如果mods目录不存在，创建一个空目录
      try {
        await fs.mkdir(modsDir, { recursive: true });
        console.log(`创建了mods目录: ${modsDir}`);
      } catch (mkdirError) {
        console.error('创建mods目录失败:', mkdirError);
        return res.status(500).json({ 
          success: false, 
          message: 'mods目录不存在且无法创建', 
          path: modsDir 
        });
      }
    }
    
    // 读取mods目录中的所有文件夹
    const files = await fs.readdir(modsDir, { withFileTypes: true });
    const modFolders = files
      .filter(file => file.isDirectory())
      .map(folder => folder.name)
      .filter(folderName => !folderName.startsWith('.')); // 过滤掉隐藏文件夹
    
    console.log(`找到 ${modFolders.length} 个模组文件夹`);
    
    res.json({ 
      success: true, 
      mods: modFolders 
    });
  } catch (error) {
    console.error('读取mods文件夹失败:', error);
    res.status(500).json({ 
      success: false, 
      message: `读取mods文件夹失败: ${error.message}` 
    });
  }
});

// 保存配置
app.post('/api/config', async (req, res) => {
  try {
    const config = req.body;
    
    // 清理可能的嵌套结构
    if (config.success !== undefined) {
      delete config.success;
    }
    if (config.data !== undefined) {
      delete config.data;
    }
    
    // 确保addAtPrefix字段存在于配置中
    if (config.addAtPrefix === undefined) {
      config.addAtPrefix = false;
    }
    
    const success = await saveConfig(config);
    if (success) {
      res.json({ success: true, message: '配置保存成功' });
    } else {
      res.status(500).json({ success: false, message: '配置保存失败' });
    }
  } catch (error) {
    res.status(500).json({ success: false, message: `保存配置失败: ${error.message}` });
  }
});



// 配置静态文件服务，指向前端构建目录
const frontendDistPath = path.join(__dirname, '../frontend/dist');
console.log(`静态文件目录: ${frontendDistPath}`);
app.use(express.static(frontendDistPath));

// 配置SPA路由处理，确保所有非API路由都返回index.html
app.get('*', (req, res) => {
  // 如果请求的是API路径，继续处理API路由
  if (req.path.startsWith('/api')) {
    return res.status(404).json({ error: 'API路径不存在' });
  }
  
  // 对于非API路径，返回index.html以支持SPA路由
  res.sendFile(path.join(frontendDistPath, 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`后端服务运行在 http://localhost:${PORT}`);
  console.log(`静态文件服务已启用，目录: ${frontendDistPath}`);
});

// 确保在进程退出时清理资源
process.on('SIGINT', () => {
  console.log('正在清理资源...');
  activePortMappings.forEach(mapping => stopPortForwarding(mapping));
  process.exit(0);
});